//
//  FindViewController.m
//  TBCellAnimation
//
//  Created by xalo on 16/4/28.
//  Copyright © 2016年 KeyTaotao. All rights reserved.
//

#import "FindViewController.h"
#import <AFNetworking.h>
#import <AFNetworking/AFNetworking.h>
#import "JokeCell.h"
#import "JokeModel.h"
#import <MJRefresh/MJRefresh.h>
#import "PhotosViewController.h"
#import "FilmViewController.h"
#define SCREENWIDTH  [UIScreen mainScreen].bounds.size.width
#define SCREENHEIGHT [UIScreen mainScreen].bounds.size.height

@interface FindViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>

@property (nonatomic, strong) NSArray *cellColors;
@property (nonatomic,retain)NSMutableDictionary *parerter;//存放请求参数的的字典
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong,nonatomic)NSMutableArray *dataArray;//存储数据的数组
@property (nonatomic,strong)NSString *str;
@property (nonatomic,assign)int startPage;//开始的页数
@property (nonatomic,strong)NSDate *refreshTime;//记录刷新时间，避免重复出刷新

@end

@implementation FindViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.refreshTime = [NSDate date];
    [self fetchDataWithUrl:@"http://japi.juhe.cn/joke/content/list.from" Parerter:self.parerter];
    self.automaticallyAdjustsScrollViewInsets = NO;
    //设置标题
    self.navigationItem.title = @"笑话";
    
    //注册xib
    [self.tableView registerNib:[UINib nibWithNibName:@"JokeCell" bundle:nil] forCellReuseIdentifier:@"JokeCell"];
   
     //下拉刷新的方法
    [self refreshData];
    //上拉加载的方法
    [self pullUpLoadData];
    
    
    
    
    
    
   
    
    
}

//下拉刷新的方法
- (void)refreshData{
    
    //添加下拉刷新功能
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
            self.startPage += 1;
            [self.parerter setValue:[NSNumber numberWithInt:self.startPage] forKey:@"page"];
            
            [self fetchDataWithUrl:@"http://japi.juhe.cn/joke/content/list.from" Parerter:self.parerter];
            self.refreshTime = [NSDate date];
   }];
}

- (void)pullUpLoadData{
    
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
       
        self.startPage -= 1;
        [self.parerter setValue:[NSNumber numberWithInt:self.startPage] forKey:@"page"];
        [self fetchDataWithUrl:@"http://japi.juhe.cn/joke/content/list.from" Parerter:self.parerter];
        [self.tableView.mj_footer beginRefreshing];
    }];
}
//解析数据
- (void)fetchDataWithUrl:(NSString *)url Parerter:(NSDictionary *)parerter{
    
    
    AFHTTPSessionManager *manager  = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:url parameters:parerter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSDictionary *resultDic = dic[@"result"];
        NSMutableArray *array = resultDic[@"data"];
        
        for (NSDictionary *object in array) {
            
            JokeModel *model = [[JokeModel alloc] init];
            [model setValuesForKeysWithDictionary:object];
            [self.dataArray addObject:model];
        }
        
        [self.dataArray removeObjectsInRange:NSMakeRange(0, self.dataArray.count - 20)];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        NSLog(@"解析失败");
    }];
}
#pragma mark -UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    JokeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JokeCell" forIndexPath:indexPath];
    JokeModel *model = self.dataArray[indexPath.row];
    cell.ContentLabel.text = model.content;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //添加动画效果
    cell.layer.transform = CATransform3DMakeTranslation(cell.frame.size.width,0, 0);
    
    [UIView animateWithDuration:1 animations:^{
        cell.layer.transform = CATransform3DMakeTranslation(0, 0, 1);
    }];
    self.str = model.content;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    CGRect titleRect = [self.str boundingRectWithSize:CGSizeMake(kWidth - 20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0] }context:nil];
    
    return titleRect.size.height + 50;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark ------懒加载
- (NSMutableDictionary *)parerter{
    
    if (!_parerter) {
        
        _parerter = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"7687ba8c97dd0767148f2ba6541f7519",@"key",@"asc",@"sort",@(1),@"page",@(20),@"pagesize",@(1418816972),@"time", nil];
    }
    return _parerter;
}
- (NSMutableArray *)dataArray{
    
    if (!_dataArray) {
        
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

@end
